<template>
  <div class="common-statistics">
    <stats-card
        title="菜谱总数" color="#CA6C65" unit="个" icon="iconfont icon-caipu"
        :value="foodStore.foodStats.recipeCount" />

    <stats-card
        title="菜谱类别" color="#6FBB69" unit="种" icon="iconfont icon-leibie"
        :value="foodStore.foodStats.categoryCount" />

    <stats-card
        title="做菜次数" color="#E4BF62" unit="次" icon="iconfont icon-cishu"
        :value="foodStore.foodStats.workCount" />

    <stats-card
        title="平均次数" color="#5470C6" unit="次/月" icon="iconfont icon-pinlv"
        :value="getAverageCount()" />
  </div>
</template>

<script setup lang="ts">
import StatsCard from '@/components/StatsCard.vue'
import { onMounted } from 'vue'
import { useFoodStore } from '@/store/food.ts'

const foodStore = useFoodStore()

onMounted(async () => {
  await foodStore.queryFoodStats()
})

const getAverageCount = () => {
  if (foodStore.queryDateType === 'month') {
    return foodStore.foodRecordList.length
  } else {
    const result = {}

    // 遍历数据，按月统计出现次数
    foodStore.foodRecordList.forEach((item) => {
      const date = new Date(item.date)
      const month = String(date.getMonth() + 1)

      if (result[month]) {
        result[month].count += 1
      } else {
        result[month] = { count: 1 }
      }
    })

    return foodStore.foodRecordList.length / Object.keys(result).length
  }
}
</script>
